package com.zxjbyte.yiyi.framework.common.util;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.zxjbyte.yiyi.framework.common.domain.auth.YiyiUser;
import com.zxjbyte.yiyi.framework.common.util.ServletXUtil;
import lombok.experimental.UtilityClass;

import javax.servlet.http.HttpServletRequest;

/**
 * 用于封装已认证用户信息的工具类，包含静态方法用于获取当前登录用户
 * 说明：
 * AuthUtil工具类 不做具体实现，只做定义封装，mock数据
 * 二次开发时，无论是Apache Shiro还是Spring-Security
 * 接可在AuthUtil工具类中封装
 *
 * 笔者后续有计划出，yiyi-spring-security系列
 * @Author zhangxingjia
 * @Date 2023/4/13 14:06
 * @Version: 1.0
 */
@UtilityClass
public class AuthUtil {

    private final String USER_REQUEST_ATTRIBUTE = "_USER_REQUEST_ATTRIBUTE_";



    /**
     * 获取用户信息
     * @return
     */
    public YiyiUser getUser(){
        return getUser(ServletXUtil.getRequest());
    }

    /**
     * 获取用户信息
     * @param request
     * @return
     */
    public YiyiUser getUser(HttpServletRequest request){
        if(ObjectUtil.isNull(request)){
            return null;
        }
        Object user = request.getAttribute(USER_REQUEST_ATTRIBUTE);
        if(ObjectUtil.isNull(user)){
            user = buildMockYiyiUser();
            request.setAttribute(USER_REQUEST_ATTRIBUTE, user);
        }
        return (YiyiUser) user;
    }

    /**
     * 获取租户id
     *
     * @return tenantId
     */
    public static String getTenantId(HttpServletRequest request) {
        YiyiUser user = getUser(request);
        return ObjectUtil.isNull(user) ? null : user.getTenantId();
    }

    /**
     * 获取租户id
     *
     * @return tenantId
     */
    public static String getTenantId() {
        YiyiUser user = getUser();
        return ObjectUtil.isNull(user) ? null : user.getTenantId();
    }

    /**
     * 获取用户id
     * @return
     */
    public Long getUserId(){
        YiyiUser user = getUser();
        return ObjectUtil.isNull(user) ? null : user.getUserid();
    }

    /**
     * 获取用户id
     * @param request
     * @return
     */
    public Long getUserId(HttpServletRequest request){
        YiyiUser user = getUser(request);
        return ObjectUtil.isNull(user) ? null : user.getUserid();
    }

    /**
     * 获取字符串用户id
     * @return
     */
    public String getUserIdAsStr(HttpServletRequest request){
        return Convert.toStr(getUserId(request));
    }

    /**
     * 获取字符串用户id
     * @return
     */
    public String getUserIdAsStr(){
        return Convert.toStr(getUserId());
    }

    /**
     * 获取用户名称
     * @return
     */
    public String getUserName(){
        YiyiUser user = getUser();
        return user != null ? user.getUserName() : null;
    }

    /**
     * 构建用户mock数据
     * 二次开发时需要重写
     * @return
     */
    private YiyiUser buildMockYiyiUser(){
        YiyiUser user = new YiyiUser();
        user.setUserid(-1L);
        user.setTenantId("000000");
        user.setUserName("admin");
        return user;
    }
}
